package com.stars.easyms.monitor.asynchronous;

import com.stars.easyms.base.asynchronous.AsynchronousTaskHolder;
import com.stars.easyms.monitor.MonitorRequestHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>className: AsynchronousTaskMonitor</p>
 * <p>description: 异步线程任务监控类</p>
 *
 * @author guoguifang
 * @date 2019-10-30 16:49
 * @since 1.3.3
 */
@Slf4j
public final class AsynchronousTaskMonitor implements MonitorRequestHandler {

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> getMonitorInfo() {
        Map<String, Object> resultMap = new LinkedHashMap<>();
        AsynchronousTaskHolder.getDuplicateList().forEach(asynchronousTask -> {
            Map<String, Object> asynchronousTaskMap = new LinkedHashMap<>();
            if (asynchronousTask.isInit()) {
                asynchronousTaskMap.put("当前排队任务数量", asynchronousTask.getQueueCount());
                asynchronousTaskMap.put("已经完成任务数量", asynchronousTask.getCompletedCount());
                asynchronousTaskMap.put("当前工作线程数量", asynchronousTask.getWorkerCount());
                asynchronousTaskMap.put("队列满等待线程数", asynchronousTask.getFullLockThreadCount());
                Map<String, Integer> errorDataCountMap = asynchronousTask.getErrorDataCountMap();
                if (errorDataCountMap.isEmpty()) {
                    asynchronousTaskMap.put("当前失败任务数量", 0);
                } else {
                    asynchronousTaskMap.put("当前失败任务明细", errorDataCountMap);
                }
                asynchronousTaskMap.put("失败丢弃任务数量", asynchronousTask.getFailedDiscardCount());
                asynchronousTaskMap.put("允许最大排队数量", asynchronousTask.getCapacity());
                asynchronousTaskMap.put("最大允许线程数量", asynchronousTask.getMaxWorkerCount());
                asynchronousTaskMap.put("允许最大重试次数", asynchronousTask.getFailRetryCount());
                asynchronousTaskMap.put("是否允许批量处理", asynchronousTask.isBatch());
                if (asynchronousTask.isBatch()) {
                    asynchronousTaskMap.put("单次批量处理最大数量", asynchronousTask.getMaxExecuteCountPerTime());
                }
            } else {
                asynchronousTaskMap.put("初始化", "未初始化");
            }
            resultMap.put(asynchronousTask.getName(), asynchronousTaskMap);
        });
        return resultMap;
    }

    @Override
    public String getModuleName() {
        return "asyn-task-threads";
    }

    @Override
    public int getOrder() {
        return 21;
    }

    @Override
    public String getIndexUrl() {
        return "asynTask";
    }
}